<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>我的商品 - 校园二手交易平台</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        /* 您可以复制index.html中的通用样式或根据需要自定义 */
        body {
            font-family: Arial, sans-serif;
            background-color: #f5f5f5;
            margin: 0;
            padding: 0;
        }
        .container {
            max-width: 1200px;
            margin: 80px auto 20px auto; /* 留出顶部导航的空间 */
            padding: 0 20px;
        }
        .section-title {
            font-size: 22px;
            font-weight: bold;
            margin-bottom: 20px;
            color: #333;
            border-left: 4px solid #4a89dc;
            padding-left: 10px;
        }
        .items-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
            gap: 20px;
        }
        /* 复制index.html中的item-card相关样式 */
        .item-card {
            background: white;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            transition: transform 0.3s, box-shadow 0.3s;
            cursor: pointer;
            height: 100%;
            display: flex;
            flex-direction: column;
        }
        .item-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        }
        .item-image {
            width: 100%;
            height: 200px;
            background-color: #f0f0f0;
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
            position: relative;
        }
        .no-image {
            display: flex;
            align-items: center;
            justify-content: center;
            color: #888;
            font-size: 14px;
        }
        .item-info {
            padding: 15px;
            flex-grow: 1;
            display: flex;
            flex-direction: column;
        }
        .item-title {
            font-weight: bold;
            margin-bottom: 8px;
            font-size: 16px;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
            overflow: hidden;
            text-overflow: ellipsis;
            line-height: 1.3;
            height: 2.6em;
        }
        .item-price {
            color: #e74c3c;
            font-size: 18px;
            font-weight: bold;
            margin-top: auto;
        }
        .item-meta {
            margin-top: 10px;
            font-size: 12px;
            color: #666;
            display: flex;
            justify-content: space-between;
        }
        .category-tag {
            background: #f0f0f0;
            padding: 3px 8px;
            border-radius: 10px;
            font-size: 11px;
        }
        .loading {
            text-align: center;
            padding: 30px;
            font-size: 18px;
            color: #666;
        }
        .no-results {
            text-align: center;
            padding: 40px 0;
            color: #666;
        }
        /* 可选: 添加侧边栏和顶部导航样式 */
        /* Style for the return to home button */
        .btn-outline {
          padding: 8px 15px; /* Slightly adjusted padding */
          background-color: transparent;
          color: #667eea;
          border: 1px solid #667eea;
          border-radius: 5px;
          text-decoration: none; /* Remove underline */
          display: inline-block; /* Treat link as button */
          transition: background-color 0.3s, color 0.3s;
          font-size: 14px; /* Adjusted font size */
        }
        .btn-outline:hover {
          background-color: #667eea;
          color: white;
        }
        /* New styles for notification badge */
        .notification-badge {
            display: none; /* Hidden by default */
            background-color: red;
            color: white;
            border-radius: 50%;
            padding: 2px 6px;
            font-size: 11px;
            margin-left: 8px;
            vertical-align: middle;
            min-width: 12px;
            text-align: center;
        }
    </style>
</head>
<body>
<!-- 您可以在这里包含顶部导航和侧边栏，或者复制index.html的结构 -->
<!-- 为简单起见，这里只包含主要内容区域 -->

<div class="container">
    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
        <h2 class="section-title" style="margin-bottom: 0;">
            我的商品 <span id="unreadCommentsBadge" class="notification-badge">新</span>
        </h2>
        <a href="index.html" class="btn-outline">返回首页</a>
    </div>
    <div id="loadingIndicator" class="loading">加载中...</div>
    <div id="noResults" class="no-results" style="display:none;">您还没有发布商品</div>
    <div class="items-grid" id="myItemsGrid">
        <!-- 用户的商品列表将通过JavaScript动态加载 -->
    </div>
</div>

<script>
    let currentUser = null;

    // 页面加载时执行
    document.addEventListener('DOMContentLoaded', function() {
        checkLogin();
        if (currentUser && currentUser.userId) {
            loadMyItems(currentUser.userId);
            checkUnreadComments(); // Initial check for unread comments
            setInterval(checkUnreadComments, 30000); // Poll every 30 seconds
        } else {
            document.getElementById('loadingIndicator').style.display = 'none';
            document.getElementById('noResults').textContent = '无法加载商品，请先登录。';
            document.getElementById('noResults').style.display = 'block';
        }
    });

    // 检查登录状态
    function checkLogin() {
        const userData = localStorage.getItem('user');
        if (!userData) {
            alert('请先登录！');
            window.location.href = 'login.html'; // 跳转到登录页面
            return;
        }
        currentUser = JSON.parse(userData);
    }

    // 加载当前用户的商品列表
    async function loadMyItems(sellerId) {
        try {
            document.getElementById('loadingIndicator').style.display = 'block';
            document.getElementById('myItemsGrid').innerHTML = '';
            document.getElementById('noResults').style.display = 'none';

            // 调用后端接口获取我的商品
            const url = `/api/items/seller/${sellerId}`;
            const response = await fetch(url);

            if (!response.ok) {
                // 尝试读取错误响应体
                const errorText = await response.text();
                console.error(`加载我的商品失败: HTTP error! status: ${response.status}, body: ${errorText}`);
                document.getElementById('loadingIndicator').style.display = 'none';
                document.getElementById('noResults').textContent = `加载失败: ${response.status} ${errorText}`;
                document.getElementById('noResults').style.display = 'block';
                return;
            }

            const items = await response.json();

            if (items.length === 0) {
                document.getElementById('noResults').style.display = 'block';
            } else {
                displayItems(items);
            }

            document.getElementById('loadingIndicator').style.display = 'none';

        } catch (error) {
            console.error('加载我的商品时发生网络错误:', error);
            document.getElementById('loadingIndicator').style.display = 'none';
            document.getElementById('noResults').textContent = '加载我的商品时发生网络错误，请检查您的网络连接。';
            document.getElementById('noResults').style.display = 'block';
        }
    }

    // 显示商品列表
    function displayItems(items) {
        const grid = document.getElementById('myItemsGrid');
        grid.innerHTML = ''; // 清空现有内容

        items.forEach(item => {
            const itemCard = document.createElement('div');
            itemCard.className = 'item-card';
            // 根据需要添加点击事件，例如跳转到商品详情页或编辑页面
            itemCard.onclick = () => viewItem(item.itemId);

            // 商品图片容器
            const itemImageDiv = document.createElement('div');
            itemImageDiv.className = 'item-image';

            // --- Modified image handling logic ---
            // 使用后端提供的 base64Image 数据显示图片
            if (item.base64Image) {
                // 直接设置背景图片
                itemImageDiv.style.backgroundImage = `url(${item.base64Image})`;
                itemImageDiv.style.backgroundSize = 'cover'; // Ensure the image covers the area
                itemImageDiv.style.backgroundPosition = 'center'; // Center the image
                itemImageDiv.style.backgroundRepeat = 'no-repeat'; // Prevent tiling
            } else {
                // Fallback if no base64 image data is available
                itemImageDiv.classList.add('no-image');
                itemImageDiv.innerHTML = '<span>暂无图片</span>';
            }
            // --- End of modified image handling logic ---

            // 商品信息
            const itemInfoDiv = document.createElement('div');
            itemInfoDiv.className = 'item-info';

            // 标题
            const titleP = document.createElement('p');
            titleP.className = 'item-title';
            titleP.textContent = item.title || '无标题';

            // 商品状态 (Optional - display status if available)
            const statusP = document.createElement('p');
            statusP.style.fontSize = '12px';
            statusP.style.color = '#666';
            statusP.textContent = `状态: ${item.status || '未知'}`;

            // 描述预览
            const descriptionDiv = document.createElement('div');
            descriptionDiv.style.fontSize = '13px';
            descriptionDiv.style.color = '#777';
            descriptionDiv.style.margin = '8px 0';
            descriptionDiv.style.display = '-webkit-box';
            descriptionDiv.style.webkitLineClamp = '2';
            descriptionDiv.style.webkitBoxOrient = 'vertical';
            descriptionDiv.style.overflow = 'hidden';
            descriptionDiv.style.textOverflow = 'ellipsis';
            descriptionDiv.style.lineHeight = '1.3';
            descriptionDiv.style.height = '2.6em';
            descriptionDiv.textContent = item.description || '暂无描述';

            // 价格
            const priceP = document.createElement('p');
            priceP.className = 'item-price';
            priceP.textContent = `¥ ${(item.price || 0).toFixed(2)}`;

            // 元数据 (分类、浏览数等)
            const metaP = document.createElement('div');
            metaP.className = 'item-meta';

            const categorySpan = document.createElement('span');
            categorySpan.className = 'category-tag';
            categorySpan.textContent = item.category || '未分类';

            const viewsSpan = document.createElement('span');
            viewsSpan.textContent = `浏览: ${item.viewCount || 0}`;

            metaP.appendChild(categorySpan);
            metaP.appendChild(viewsSpan);

            // Delete Button
            const deleteBtn = document.createElement('button');
            deleteBtn.textContent = '删除';
            deleteBtn.className = 'btn'; // Use existing button style or define a new one
            deleteBtn.style.marginTop = '10px'; // Add some space above the button
            deleteBtn.style.backgroundColor = '#e74c3c'; // Example delete button color
            deleteBtn.style.hoverBackgroundColor = '#c0392b';
            deleteBtn.onclick = (e) => { // Use arrow function to preserve 'this' context if needed, and pass event
                e.stopPropagation(); // Prevent itemCard click event from triggering
                deleteItem(item.itemId);
            };

            // 组装商品卡片
            itemInfoDiv.appendChild(titleP);
            itemInfoDiv.appendChild(statusP); // Add status to item info
            itemInfoDiv.appendChild(descriptionDiv);
            itemInfoDiv.appendChild(priceP);
            itemInfoDiv.appendChild(metaP);
            itemInfoDiv.appendChild(deleteBtn); // Add delete button

            itemCard.appendChild(itemImageDiv);
            itemCard.appendChild(itemInfoDiv);

            grid.appendChild(itemCard);
        });
    }

    // Function to handle item deletion
    async function deleteItem(itemId) {
        if (confirm('确定要删除这个商品吗？')) {
            try {
                const response = await fetch(`/api/items/${itemId}`, {
                    method: 'DELETE'
                });

                if (response.ok) {
                    alert('商品删除成功！');
                    // Reload the items list after successful deletion
                    loadMyItems(currentUser.userId);
                } else {
                    const errorText = await response.text();
                    alert(`删除失败: ${errorText}`);
                    console.error('删除商品失败:', errorText);
                }
            } catch (error) {
                console.error('删除商品时发生网络错误:', error);
                alert('删除商品时发生网络错误，请检查您的网络连接。');
            }
        }
    }

    // View item detail function (already exists)
    function viewItem(itemId) {
        window.location.href = `item-detail.html?id=${itemId}`;
    }

    // 假设 logout 函数用于退出登录
    function logout() {
        localStorage.removeItem('user');
        window.location.href = 'login.html';
    }

    // Function to check for unread comments
    async function checkUnreadComments() {
        const currentUser = getCurrentUser();
        if (!currentUser || !currentUser.userId) {
            console.warn("User not logged in, cannot check for unread comments.");
            // Optionally hide the badge if user is not logged in
            const unreadCommentsBadge = document.getElementById('unreadCommentsBadge');
            if (unreadCommentsBadge) unreadCommentsBadge.style.display = 'none';
            return;
        }

        try {
            const response = await fetch(`/api/messages/unread-comments/seller/${currentUser.userId}`);
            if (!response.ok) {
                console.error("Failed to fetch unread comments status:", response.status, response.statusText);
                return;
            }
            const hasUnread = await response.json();
            const unreadCommentsBadge = document.getElementById('unreadCommentsBadge');
            if (unreadCommentsBadge) {
                if (hasUnread) {
                    unreadCommentsBadge.style.display = 'inline-block';
                    // unreadCommentsBadge.textContent = '新'; // Already set in HTML
                } else {
                    unreadCommentsBadge.style.display = 'none';
                }
            }
        } catch (error) {
            console.error("Error checking unread comments:", error);
        }
    }

</script>
</body>
</html>